package com.device.api.controller;


import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.device.api.entity.*;

import com.device.api.entity.enums.QcCodeEnum;
import com.device.api.entity.vo.QcVo;
import com.device.api.mapper.PudongDeviceConfigMapper;
import com.device.api.mapper.QcDataMapper;
import com.device.api.r.Result;
import com.device.api.request.DeviceDataSwitchRequest;

import com.device.api.request.DeviceReadDataRequest;
import com.device.api.request.DeviceUploadFrequencyRequest;
import com.device.api.service.IDeviceApiService;
import com.device.api.service.IPudongDeviceStatusService;
import com.device.api.utils.EnumUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sys/api")
public class DeviceApiController {

    @Autowired
    private IDeviceApiService deviceApiService;

    @Autowired
    private PudongDeviceConfigMapper pudongDeviceConfigMapper;
    
    @Autowired
    private IPudongDeviceStatusService pudongDeviceStatusService;

    @Autowired
    private QcDataMapper qcDataMapper;

    /**
     * 设备运行状态信息接口
     * @return（设备运行状态，运行时长，停用次数，停用时长，传输中断次数，故障次数）。
     */
    @GetMapping("/device/running/status")
    public Result<?> deviceStatus(@RequestParam(name = "deviceNo")String deviceNo){
        
        QueryWrapper<PudongDeviceStatus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_no",deviceNo);
        PudongDeviceStatus deviceRunningStatusInfo = pudongDeviceStatusService.getOne(queryWrapper);
        return Result.OK(deviceRunningStatusInfo);

    }

    @GetMapping("/device/running/status/list")
    public Result<?> deviceStatusList(){
        List<PudongDeviceStatus> list = pudongDeviceStatusService.list();
        return Result.OK(list);

    }


    @PostMapping ("/device/add")
    public Result<?> deviceAdd(@RequestBody PudongDeviceConfig pudongDeviceConfig){
        Result result = new Result<>();
        if (pudongDeviceConfig.getSnCode()==null){
            return result.error500("请填写SN码");
        }
        if (pudongDeviceConfig.getImei()==null){
            return result.error500("请填写串码");
        }
        pudongDeviceConfig.setDeviceNo(pudongDeviceConfig.getSnCode());

        pudongDeviceConfig.setDeviceCtwingId(pudongDeviceConfig.getSnCode()+pudongDeviceConfig.getImei());

        if (pudongDeviceConfigMapper.selectList(new QueryWrapper<PudongDeviceConfig>().eq("sn_code",pudongDeviceConfig.getSnCode())).size()>0){
            return result.error500("SN码已存在");
        }

        int insert = pudongDeviceConfigMapper.insert(pudongDeviceConfig);
        if (insert>0){
            return result.success("添加成功");

        }
        return result.error500("添加失败");
    }

    @PutMapping ("/device/edit")
    public Result<?> deviceEdit(@RequestBody PudongDeviceConfig pudongDeviceConfig){
//        Result result = new Result<>();

    UpdateWrapper<PudongDeviceConfig> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("sn_code",pudongDeviceConfig.getSnCode());

      pudongDeviceConfigMapper.update(pudongDeviceConfig,updateWrapper);

    return Result.OK("成功");
    }

    @DeleteMapping ("/device/delete")
    public Result<?> delete(@RequestParam(value = "deviceNo") String deviceNo){
        return deviceApiService.delete(deviceNo);
    }




    /**
     * 获取所有连接的设备信息接口
     * @return （设备号，所在站点，设备名称，设备型号，SN码，设备产地，设备生产日期，传输方式，传输频率）。
     */
    @GetMapping("/device/list")
    public Result<?> deviceList(){
        List<PudongDeviceConfig> pudongDeviceConfigs = pudongDeviceConfigMapper.selectList(new QueryWrapper<>());
        return  Result.OK(pudongDeviceConfigs);
    }

    /**
     * 设备停止传输和启动传输的接口。
     * @return 200成功 500失败
     */
    @PutMapping("/device/data/switch")
    public Result<?> deviceDataSwitch(@RequestBody DeviceDataSwitchRequest request){


        return  deviceApiService.updateDeviceDataSwitch(request);
    }

    /**
     * 改变运行设备传输频率的接口。
     * @return 200成功 500失败
     */
    @PutMapping("/device/upload/frequency")
    public Result<?> deviceUploadFrequency(@RequestBody DeviceUploadFrequencyRequest request){

        return    deviceApiService.updateDeviceUploadFrequency(request);
    }

    /**
     * 校正设备时间
     * @return 200成功 500失败
     */
    @PutMapping("/device/time/calibration")
    public Result<?> timeCalibration(@RequestBody JSONObject jsonObject){
        Object deviceNo = jsonObject.get("deviceNo");
        return deviceApiService.timeCalibration(deviceNo);
    }

    /**
     * 补要历史设备数据
     * @return 200成功 500失败
     */
    @PostMapping("/device/read/data")
    public Result<?> deviceReadData(@RequestBody DeviceReadDataRequest request){

        return deviceApiService.deviceReadData(request);
    }

    /**
     * 设置设备ip
     * @return 200成功 500失败
     */
    @PostMapping("/device/set/ip")
    public Result<?> deviceSetIp(@RequestBody JSONObject jsonObject){

        return deviceApiService.deviceSetIp(jsonObject);
    }

    /**
     * 获取设备时间
     * @return 200成功 500失败
     */
    @GetMapping("/device/time/get")
    public Result<?> getDeviceTime(@RequestParam(value = "deviceNo") String deviceNo){

        return deviceApiService.getDeviceTime(deviceNo);
    }



    /**
     * 数据一级质控
     * @return 200成功 500失败
     */
    @GetMapping("/device/qc/examining/report")
    public Result<?> deviceQcExaminingReport(@RequestParam(name = "deviceNo",required = false) String deviceNo,
                                             @RequestParam(name = "pageNo",required = false)Integer pageNo,
                                             @RequestParam(name = "pageSize",required = false)Integer pageSize,
                                             @RequestParam(name = "startTime",required = false)String startTime,
                                             @RequestParam(name = "endTime",required = false)String endTime ){

        Page<QcVo> result = deviceApiService.deviceQcExaminingReport(deviceNo,pageNo,pageSize,startTime,endTime);
        return Result.OK(result);
    }

    /**
     * 设备故障质控码
     * @return 200成功 500失败
     */
    @GetMapping("/device/qc/fault/code")
    public Result<?> deviceQcFaultCode(@RequestParam(name = "deviceNo",required = false) String deviceNo,@RequestParam(name = "pageNo",required = false)String pageNo,@RequestParam(name = "pageSize",required = false)String pageSize,@RequestParam(name = "startTime",required = false)String startTime,@RequestParam(name = "endTime",required = false)String endTime ){
//        List<QcCodeEnum> qcCodeEnums = deviceApiService.deviceQcFaultCode();
        List<Map<String, Object>> qcCodeEnums = EnumUtils.enumToListMap(QcCodeEnum.class);
        return Result.OK(qcCodeEnums);
    }

    @PostMapping("/device/auth")
    public JSONObject deviceAuth(@RequestBody JSONObject message){
//        System.out.println(message);

      return   deviceApiService.deviceAuth(message);

    }


    /**
     * 一级质控
     * @return 200成功 500失败
     */
    @GetMapping("/device/qc/list")
    public Result<?> deviceQcList(@RequestParam(name = "deviceNo",required = false) String deviceNo,
                                             @RequestParam(name = "startTime",required = false)String startTime,
                                             @RequestParam(name = "endTime",required = false)String endTime ){

        QueryWrapper<QcData> qcDataQueryWrapper = new QueryWrapper<>();
        if (!deviceNo.equals("")&&deviceNo!=null) {
            System.out.println(11);
            qcDataQueryWrapper.eq("sn_code", deviceNo);

        }
        if (!startTime.equals("")&&startTime!=null&& !endTime.equals("")&& endTime!=null) {
            System.out.println(22);
            qcDataQueryWrapper.between("create_time",startTime,endTime);
        }
        List<QcData> result = qcDataMapper.selectList(qcDataQueryWrapper);


        return Result.OK(result);
    }



}
